package com.b.sts.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.b.sts.entity.CarEntity;
import com.b.sts.exception.FailException;
import com.b.sts.mapper.CarMapper;
import com.b.sts.service.CarService;
import com.b.sts.service.ProductService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author b
 * @since 2023-07-12
 */
@Service
public class CarServiceImp extends ServiceImpl<CarMapper, CarEntity> implements CarService {
    @Resource
    CarMapper mapper;
    @Resource
    ProductService productService;

    @Override
    public CarEntity get(Integer id) {
        return mapper.selectById(id);
    }

    @Override
    public List<CarEntity> list(CarEntity entity) {
        LambdaQueryWrapper<CarEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.setEntity(entity);
        return mapper.selectList(wrapper).stream()
                .peek(e -> e.setProductEntity(productService.getById(e.getProductId())))
                .collect(Collectors.toList());
    }

    @Override
    public boolean add(CarEntity entity) {
        List<CarEntity> list = this.list(entity);
        if (CollUtil.isNotEmpty(list)) {
            throw new FailException("已存在购物车");
        }
        return mapper.insert(entity) > 0;
    }

    @Override
    public boolean del(Integer id) {
        return mapper.deleteById(id) > 0;
    }

    @Override
    public boolean update(CarEntity entity) {
        return mapper.updateById(entity) > 0;
    }

    @Override
    public List<CarEntity> my(CarEntity entity) {
        return list(entity);
    }
}
